package cn.interestingshop.dao;

import java.sql.*;

public class BaseDao {
    String driver="com.mysql.cj.jdbc.Driver";
    String url="jdbc:mysql://localhost:3306/interesting_shop_db?serverTimezone=GMT-8&characterEncoding=utf-8";
    String username="root";
    String password="123456";

    /**
     * 获取连接
     * @return
     */
    public Connection getConnection(){
        Connection conn=null;
        try {
            //1.加载驱动
            Class.forName(driver);
            //2.创建连接
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭资源
     */
    public void closeAll(ResultSet rs, PreparedStatement ps,Connection conn){
        //8.释放资源，关闭连接
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
       if(ps!=null){
           try {
               ps.close();
           } catch (SQLException throwables) {
               throwables.printStackTrace();
           }
       }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 通用增删改方法
     * @param sql
     * @param obj
     * @return
     */
    public int executeUpdate(String sql,Object[] obj){
        Connection conn=null;
        PreparedStatement ps=null;
        int rs=0;
        try {
            //1.加载驱动
            //2.创建连接
            conn = getConnection();
            //3.定义sql语句
            //4.创建执行对象
            ps=conn.prepareStatement(sql);
            //5.填充参数
            if(obj!=null){
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i+1,obj[i]);
                }
            }
            //6.执行sql语句
            rs=ps.executeUpdate();
            //7.分析返回结果
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //8.释放资源，关闭连接
            closeAll(null,ps,conn);
        }
        return rs;
    }

}
